package com.wangzhou.head.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * servlet的入门
 * 
 * @author zjx
 *
 */
public class HelloHeadServlet extends HttpServlet
{

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		this.doPost(request, response);
	}
	
	/**
	 * servlet的核心代码
	 */
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		request.setCharacterEncoding("UTF-8");
		String method = request.getParameter("method");
		System.out.println("--HelloHeadServlet--doPost--" + method);
		String url = "/WEB-INF/head/main.jsp" ;
		if("helloJSON".equalsIgnoreCase(method))
		{
			this.helloJSON(request,response);
		}else
		{
			request.getRequestDispatcher(url).forward(request, response);
		}
	}
	
	/**
	 * 第一个json,ajax返回的数据
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void helloJSON(HttpServletRequest request, HttpServletResponse response) throws IOException
	{
		response.setCharacterEncoding("UTF-8");
		String json = "{'code':200,'info':'success'}"; 
		String flag = request.getParameter("flag");
		if("1".equalsIgnoreCase(flag))
		{
			json = "{'code':200,'info':'success1"+ flag +"'}"; 
		}else if("2".equalsIgnoreCase(flag))
		{
			json = "{'code':200,'info':'success2"+ flag +"'}"; 
		}else
		{
			json = "{'code':200,'info':'success"+ flag +"'}"; 
		}
		//String json = "<?xml version='1.0' encoding='UTF-8'?><root><code>200</code><info>success</info></root>";
		response.setContentType("text/html;charst='UTF-8'");
		PrintWriter out = response.getWriter();
		out.print(json);
		out.flush();
	}
	
}
